package pkg

import (
	"errors"
	"fmt"
	"github.com/golang-jwt/jwt/v4"
	"time"
	"yuekaoHouse/api/appconfig"
)

// @secretKey: JWT 加解密密钥
// @iat: 时间戳
// @seconds: 过期时间，单位秒
// @payload: 数据载体

// 生成token
func GetJwtToken(payload string) (string, error) {
	//动态配置
	res := appconfig.AppData.JwtToken
	secretKey := res.AccessSecret
	iat := time.Now().Unix()
	seconds := res.AccessExpire

	claims := make(jwt.MapClaims)
	claims["exp"] = iat + seconds
	claims["iat"] = iat
	claims["payload"] = payload
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	return token.SignedString([]byte(secretKey))
}

// 解析token
func ParseToken(tokenString string) (interface{}, error) {
	//jwt.Parse()
	res := appconfig.AppData.JwtToken
	secretKey := res.AccessSecret

	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		return []byte(secretKey), nil
	})
	if err != nil {
		return "", errors.New("token解析失败")
	}
	if !token.Valid {
		return "", errors.New("token失效")
	}
	if claims, ok := token.Claims.(jwt.MapClaims); ok {
		fmt.Println(claims["foo"], claims["nbf"])
		return claims["payload"], nil
	}
	return "", errors.New("token获取失败")
}
